package com.hisense.hiioc.hismartplate.service;

import com.alibaba.fastjson.JSONObject;
import com.hisense.hiioc.hismartplate.exception.HttpNotFoundException;
import com.hisense.hiioc.hismartplate.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther:biexiande@hisense.com
 * @date:2018/12/24 19:08
 * @des
 */
@Service
public class SpeechService {

    private static final String OAUTHURL = "http://openapi.baidu.com/oauth/2.0/token";
    private static final String TOAUDIOURL = "http://tsn.baidu.com/text2audio?"+
            "tex={tex}&per=0&spd=5&pit=5&vol=5&lan=zh&cuid=1234567JAVA&aue=3&ctp=1&tok={tok}";

    public static final Logger LOGGER = LoggerFactory.getLogger(SpeechService.class);
    @Value("${baiduaip.apiKey:YuCOUME7rgrn9rGSV1gjR8Z9}")
    private String apiKey;
    @Value("${baiduaip.secretKey:ymaNtxpgthA4YtB3uZ5gcrZbobGvv6Ol}")
    private String secretKey;

    @Autowired
    RestTemplate restTemplate;

    public byte[] text2AudioService(String txt){
        String token= this.getToken();
        Map<String,Object> variables= new HashMap();
        variables.put("tex",StringUtil.urlEncode(txt));
        variables.put("tok",token);
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Resource> httpEntity = new HttpEntity<Resource>(headers);
        ResponseEntity<byte[]> response = restTemplate.exchange(TOAUDIOURL, HttpMethod.GET,
                httpEntity, byte[].class,variables);
        return response.getBody();
    }

    private String getToken(){
        String getTokenURL = OAUTHURL + "?grant_type=client_credentials"
                + "&client_id=" + StringUtil.urlEncode(apiKey) + "&client_secret=" + StringUtil.urlEncode(secretKey);
        ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(getTokenURL, JSONObject.class);
        if(200!=responseEntity.getStatusCodeValue()){
            throw new HttpNotFoundException();
        }
        return responseEntity.getBody().getString("access_token");
    }


}